package botlab.control;

import botlab.Game;
import com.jme3.export.InputCapsule;
import com.jme3.export.JmeExporter;
import com.jme3.export.JmeImporter;
import com.jme3.export.OutputCapsule;
import com.jme3.input.InputManager;
import com.jme3.renderer.RenderManager;
import com.jme3.renderer.ViewPort;
import com.jme3.scene.Spatial;
import com.jme3.scene.control.Control;
import java.io.IOException;

/**
 *
 * @author Quentin
 */
public abstract class BaseControl implements Control
{
    protected InputManager inputManager;
    protected Spatial spatial;
    protected boolean enabled;

    public BaseControl()
    {
        this.inputManager = Game.getApp().getInputManager();
        this.enabled = true;
    }

    public void setSpatial(Spatial spatial)
    {
        if (this.spatial != null && spatial!=null)
        {
            throw new IllegalStateException(
                    "This control has already been added to a Spatial");
        }
        this.spatial = spatial;
    }

    public Spatial getSpatial()
    {
        return spatial;
    }

    public void setEnabled(boolean enabled)
    {
        this.enabled = enabled;
    }

    public boolean isEnabled()
    {
        return enabled;
    }

    public void removeControl()
    {
        spatial.removeControl(this);
    }

    /**
     * To be implemented in subclass.
     */
    protected abstract void controlUpdate(float tpf);
    public abstract Control cloneForSpatial(Spatial spatial);
    
    public void update(float tpf)
    {
        if (!enabled)
        {
            return;
        }

        controlUpdate(tpf);
    }

    public void render(RenderManager rm, ViewPort vp)
    {
        
    }

    @Override
    public void write(JmeExporter ex) throws IOException
    {
        OutputCapsule oc = ex.getCapsule(this);
        oc.write(enabled, "enabled", true);
        oc.write(spatial, "spatial", null);
        // write custom variables ....
    }

    @Override
    public void read(JmeImporter im) throws IOException
    {
        InputCapsule ic = im.getCapsule(this);
        enabled = ic.readBoolean("enabled", true);
        spatial = (Spatial) ic.readSavable("spatial", null);
        // read custom variables ....
    }

}
